package com.powernode.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.powernode.common.Code;
import com.powernode.constants.RedisKey;
import com.powernode.resp.Result;
import com.powernode.util.TokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class TokenInterceptor implements HandlerInterceptor {

    private TokenUtil tokenUtil;

    private StringRedisTemplate stringRedisTemplate;

    public TokenInterceptor(TokenUtil tokenUtil, StringRedisTemplate stringRedisTemplate) {
        this.tokenUtil = tokenUtil;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public TokenInterceptor() {
    }

    /*执行controller之前执行*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        int authResult =0;

        /*1 获取请求头的 token*/
        String authorization = request.getHeader("Authorization");
        if (authorization!=null&&authorization.contains("Bearer ")){
            String token = authorization.replaceAll("Bearer ", "");
            /*2解析token*/
            Claims claims = tokenUtil.readJwt(token);
            if (claims!=null){
                /*解析成功*/
                /*判断 请求的 uid  和 token中的uid 是否一样*/
                String uid = request.getHeader("uid");
              /*  Object uidFromToken = claims.get("uid");
                if (!uid.equals(uidFromToken.toString())){
                    不是同一个用户
                    authResult=1;
                }else {
                    是同一个用户 而且登录
                    request.setAttribute("uid",uid);
                }*/
                /*判断 redis中是否存在 token的键  存在 登录状态 不存在 注销状态*/
                Boolean hasKey = stringRedisTemplate.hasKey(RedisKey.YLB_LOGIN_TOKEN + token);
                if (!hasKey){
                    authResult=1;
                }else {
                    request.setAttribute("uid",uid);
                }
            }else {
                /*解析失败*/
                authResult=2;
            }
        }else {
            /*不存在token*/
            authResult=3;
        }

        /*通过 authResult  进行统一处理*/
        if (authResult>0){ 
            response.setContentType("application/json;charset=UTF-8");
            /*给前端提示*/
            Result result = new Result();
            result.setCodeEnum(Code.TOKEN_INVALIDATE);
            /*响应*/
            PrintWriter writer = response.getWriter();
            /*将result 转换为 json数据*/
            String json = JSONObject.toJSONString(result);
            writer.write(json);
            writer.flush();
            /*不能放行*/
            return  false;
        }

        /*放行*/
        return true;
    }
}
